package dr.mini.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import dr.mini.dao.MemberDao;
import dr.mini.dao.MemberDaoImpl;
import dr.mini.domain.MemberCommand;
import dr.mini.validator.MemberValidator;

@Controller
public class InsertController{

	private String formViewName = "/insertForm";
	private MemberDao memberDao;
	@Autowired
	public void setMemberDao(MemberDao memberDao) {
		this.memberDao = memberDao;
	}

	@RequestMapping(value="/insert.do", method=RequestMethod.GET)
	public String form(){
		return formViewName;
	}
	
	@ModelAttribute
	public MemberCommand formBacking() {
		return new MemberCommand();
	}
	
	@RequestMapping(value="/insert.do", method=RequestMethod.POST)
	public String submit(@Valid MemberCommand memberCommand, BindingResult result){
		
		    if(result.hasErrors()){
		    	return formViewName;
		    }
		    memberDao.insertMember(memberCommand);
			return "redirect:/list.do";
	}
	@InitBinder
	protected void initBinder(WebDataBinder binder){
		binder.setValidator(new MemberValidator());
	}
	
}
